import 'package:flutter/material.dart';
import '../services/music_api_service.dart';
import '../services/audio_quality_service.dart';
import '../models/song.dart';
import '../models/music_source.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SearchBarWidget extends StatefulWidget {
  final Function(List<Song>, String) onSearchResults;
  final VoidCallback onSearchStarted;
  final VoidCallback? onTap;

  const SearchBarWidget({
    super.key,
    required this.onSearchResults,
    required this.onSearchStarted,
    this.onTap,
  });

  @override
  State<SearchBarWidget> createState() => SearchBarWidgetState();
}

class SearchBarWidgetState extends State<SearchBarWidget> {
  final TextEditingController _controller = TextEditingController();
  final MusicApiService _apiService = MusicApiService();
  final AudioQualityService _qualityService = AudioQualityService();
  MusicSource _selectedSource = MusicSource.netease;

  static const String _lastSourceKey = 'last_selected_source';

  @override
  void initState() {
    super.initState();
    _loadLastSelectedSource();
    // 监听音质服务的状态变化
    _qualityService.addListener(_onQualityChanged);
  }

  void _onQualityChanged() {
    if (mounted) {
      setState(() {});
    }
  }

  Future<void> _loadLastSelectedSource() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final value = prefs.getString(_lastSourceKey);
      if (value != null) {
        final source = MusicSource.fromString(value);
        if (mounted) {
          setState(() {
            _selectedSource = source;
          });
        }
      }
    } catch (e) {
      // 读取失败则忽略，保持默认源
    }
  }

  Future<void> _saveLastSelectedSource(MusicSource source) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_lastSourceKey, source.value);
    } catch (e) {
      // 写入失败则忽略
    }
  }

  /// 公开的搜索方法，允许外部设置关键词并触发搜索
  Future<void> searchWithKeyword(String keyword) async {
    if (keyword.trim().isEmpty) return;
    
    _controller.text = keyword;
    await _performSearch();
  }

  /// 获取当前选择的音质
  AudioQuality get selectedQuality => _qualityService.selectedQuality;

  Future<void> _performSearch() async {
    final query = _controller.text.trim();
    if (query.isEmpty) return;

    widget.onSearchStarted();

    try {
      print('开始搜索: 关键词="$query", 音乐源=${_selectedSource.value}');
      final results = await _apiService.searchMusic(
        keyword: query,
        source: _selectedSource,
        count: 50,
      );
      print('搜索完成: 找到${results.length}首歌曲');
      widget.onSearchResults(results, query);
    } catch (e, stackTrace) {
      print('搜索异常: $e');
      print('堆栈跟踪: $stackTrace');
      if (mounted) {
        String errorMessage = '搜索失败';
        
        if (e.toString().contains('Connection closed')) {
          errorMessage = '网络连接中断，请检查网络后重试';
        } else if (e.toString().contains('timeout')) {
          errorMessage = '请求超时，请稍后重试';
        } else if (e.toString().contains('403')) {
          errorMessage = '访问被限制，请稍后重试';
        } else if (e.toString().contains('已重试')) {
          errorMessage = '网络不稳定，请检查网络连接';
        }
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(Icons.error_outline, color: Colors.white),
                SizedBox(width: 8),
                Expanded(child: Text(errorMessage)),
                TextButton(
                  onPressed: () {
                    ScaffoldMessenger.of(context).hideCurrentSnackBar();
                    _performSearch();
                  },
                  child: Text('重试', style: TextStyle(color: Colors.white)),
                ),
              ],
            ),
            backgroundColor: Theme.of(context).colorScheme.error,
            duration: Duration(seconds: 5),
          ),
        );
        widget.onSearchResults([], query);
      }
    }
  }

  void _showSourceSelector() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => DraggableScrollableSheet(
        initialChildSize: 0.85,
        minChildSize: 0.6,
        maxChildSize: 0.95,
        builder: (context, scrollController) => _SourceSelectorContent(
          qualityService: _qualityService,
          selectedSource: _selectedSource,
          onSourceSelected: (source) {
            setState(() {
              _selectedSource = source;
            });
            _saveLastSelectedSource(source);
            Navigator.pop(context);
          },
        ),
      ),
    );
  }

  /// 根据音源类型返回相应的图标
  IconData _getSourceIcon(MusicSource source) {
    switch (source) {
      case MusicSource.netease:
        return Icons.music_note;
      case MusicSource.tencent:
        return Icons.queue_music;
      case MusicSource.migu:
        return Icons.audiotrack;
      case MusicSource.kugou:
        return Icons.library_music;
      case MusicSource.kuwo:
        return Icons.album;
      case MusicSource.ximalaya:
        return Icons.radio;
      case MusicSource.tidal:
        return Icons.waves;
      case MusicSource.spotify:
        return Icons.music_video;
      case MusicSource.ytmusic:
        return Icons.play_circle;
      case MusicSource.qobuz:
        return Icons.high_quality;
      case MusicSource.joox:
        return Icons.headphones;
      case MusicSource.deezer:
        return Icons.speaker;
      case MusicSource.apple:
        return Icons.apple;
      case MusicSource.buguyy:
        return Icons.library_music_outlined; // 布谷音乐
      case MusicSource.mitu:
        return Icons.music_note; // 米兔音乐
      case MusicSource.alger:
        return Icons.music_note; // Alger
    }
  }

  @override
  void dispose() {
    // 移除音质服务的监听器
    _qualityService.removeListener(_onQualityChanged);
    _controller.dispose();
    _apiService.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
        borderRadius: BorderRadius.circular(28),
      ),
      child: Row(
        children: [
          // 音乐源选择按钮
          GestureDetector(
            onTap: _showSourceSelector,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              margin: const EdgeInsets.only(left: 8),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
                  width: 1,
                ),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    _getSourceIcon(_selectedSource),
                    size: 16,
                    color: Theme.of(context).colorScheme.primary,
                  ),
                  const SizedBox(width: 6),
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _selectedSource.displayName,
                        style: Theme.of(context).textTheme.labelMedium?.copyWith(
                          color: Theme.of(context).colorScheme.onSurface,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Text(
                        '${_qualityService.selectedQuality.displayName}',
                        style: Theme.of(context).textTheme.labelSmall?.copyWith(
                          color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
                          fontSize: 10,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(width: 4),
                  Icon(
                    Icons.keyboard_arrow_down,
                    size: 16,
                    color: Theme.of(context).colorScheme.primary,
                  ),
                ],
              ),
            ),
          ),
          
          // 搜索输入框
          Expanded(
            child: TextField(
              controller: _controller,
              decoration: const InputDecoration(
                hintText: '搜索歌曲、歌手、专辑...',
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
              ),
              textInputAction: TextInputAction.search,
              onSubmitted: (_) => _performSearch(),
              onTap: widget.onTap, // 点击搜索框时触发回调
            ),
          ),
          
          // 搜索按钮
          IconButton(
            onPressed: _performSearch,
            icon: const Icon(Icons.search),
            tooltip: '搜索',
          ),
        ],
      ),
    );
  }
}

// 音乐源选择界面的独立状态ful widget
class _SourceSelectorContent extends StatefulWidget {
  final AudioQualityService qualityService;
  final MusicSource selectedSource;
  final Function(MusicSource) onSourceSelected;

  const _SourceSelectorContent({
    required this.qualityService,
    required this.selectedSource,
    required this.onSourceSelected,
  });

  @override
  State<_SourceSelectorContent> createState() => _SourceSelectorContentState();
}

class _SourceSelectorContentState extends State<_SourceSelectorContent> {
  late MusicSource _selectedSource;

  @override
  void initState() {
    super.initState();
    _selectedSource = widget.selectedSource;
    // 监听音质服务的变化
    widget.qualityService.addListener(_onQualityChanged);
  }

  void _onQualityChanged() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void dispose() {
    widget.qualityService.removeListener(_onQualityChanged);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        children: [
          // 拖拽指示器
          Container(
            width: 40,
            height: 4,
            margin: const EdgeInsets.symmetric(vertical: 12),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.3),
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          
          // 标题
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Row(
              children: [
                Icon(
                  Icons.library_music,
                  color: Theme.of(context).colorScheme.primary,
                  size: 24,
                ),
                const SizedBox(width: 8),
                Text(
                  '选择音乐源',
                  style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 16),
          
          // 音质选择区域
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 20),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.high_quality,
                      color: Theme.of(context).colorScheme.primary,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '音质选择',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: AudioQuality.values.map((quality) {
                    final isSelected = quality == widget.qualityService.selectedQuality;
                    return GestureDetector(
                      onTap: () async {
                        await widget.qualityService.setQuality(quality);
                        // 立即刷新UI以显示高亮状态
                        if (mounted) {
                          setState(() {});
                        }
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                        decoration: BoxDecoration(
                          color: isSelected 
                              ? Theme.of(context).colorScheme.primary
                              : Theme.of(context).colorScheme.surface,
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(
                            color: isSelected 
                                ? Theme.of(context).colorScheme.primary
                                : Theme.of(context).colorScheme.outline.withOpacity(0.5),
                            width: 1,
                          ),
                        ),
                        child: Text(
                          '${quality.displayName} (${quality.bitrate}k)',
                          style: Theme.of(context).textTheme.bodySmall?.copyWith(
                            color: isSelected 
                                ? Theme.of(context).colorScheme.onPrimary
                                : Theme.of(context).colorScheme.onSurface,
                            fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 16),
          
          // 音乐源选择标题
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Row(
              children: [
                Icon(
                  Icons.source,
                  color: Theme.of(context).colorScheme.primary,
                  size: 20,
                ),
                const SizedBox(width: 8),
                Text(
                  '音乐源选择',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 12),
          
          // 可滚动的音乐源网格
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
              child: GridView.builder(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                  childAspectRatio: 1.0,
                ),
                itemCount: MusicSource.values.length,
                itemBuilder: (context, index) {
                  final source = MusicSource.values[index];
                  final isSelected = source == _selectedSource;
                  
                  return GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedSource = source;
                      });
                      widget.onSourceSelected(source);
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        color: isSelected 
                            ? Theme.of(context).colorScheme.primaryContainer
                            : Theme.of(context).colorScheme.surfaceVariant,
                        borderRadius: BorderRadius.circular(16),
                        border: isSelected 
                            ? Border.all(
                                color: Theme.of(context).colorScheme.primary,
                                width: 2,
                              )
                            : Border.all(
                                color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
                                width: 1,
                              ),
                        boxShadow: isSelected ? [
                          BoxShadow(
                            color: Theme.of(context).colorScheme.primary.withOpacity(0.2),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ] : null,
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          // 音源图标
                          Container(
                            width: 48,
                            height: 48,
                            decoration: BoxDecoration(
                              color: isSelected 
                                  ? Theme.of(context).colorScheme.primary
                                  : Theme.of(context).colorScheme.primary.withOpacity(0.8),
                              shape: BoxShape.circle,
                              boxShadow: [
                                BoxShadow(
                                  color: (isSelected 
                                      ? Theme.of(context).colorScheme.primary
                                      : Theme.of(context).colorScheme.primary.withOpacity(0.8))
                                      .withOpacity(0.3),
                                  blurRadius: 8,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                            ),
                            child: Icon(
                              _getSourceIcon(source),
                              color: Colors.white,
                              size: 24,
                            ),
                          ),
                          
                          const SizedBox(height: 8),
                          
                          // 音源名称
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 4),
                            child: Text(
                              source.displayName,
                              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                                color: isSelected 
                                    ? Theme.of(context).colorScheme.onPrimaryContainer
                                    : Theme.of(context).colorScheme.onSurfaceVariant,
                                fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                                fontSize: 12,
                              ),
                              textAlign: TextAlign.center,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 根据音源类型返回相应的图标
  IconData _getSourceIcon(MusicSource source) {
    switch (source) {
      case MusicSource.netease:
        return Icons.music_note;
      case MusicSource.tencent:
        return Icons.queue_music;
      case MusicSource.migu:
        return Icons.audiotrack;
      case MusicSource.kugou:
        return Icons.library_music;
      case MusicSource.kuwo:
        return Icons.album;
      case MusicSource.ximalaya:
        return Icons.radio;
      case MusicSource.tidal:
        return Icons.waves;
      case MusicSource.spotify:
        return Icons.music_video;
      case MusicSource.ytmusic:
        return Icons.play_circle;
      case MusicSource.qobuz:
        return Icons.high_quality;
      case MusicSource.joox:
        return Icons.headphones;
      case MusicSource.deezer:
        return Icons.speaker;
      case MusicSource.apple:
        return Icons.apple;
      case MusicSource.buguyy:
        return Icons.library_music_outlined;
      case MusicSource.mitu:
        return Icons.music_note;
      case MusicSource.alger:
        return Icons.music_note;
    }
  }
}